import React from 'react';
import { connect } from 'dva';
import { Card, Form, Table, Collapse, Spin, Alert, Tabs } from 'antd';
import ReactJson from 'react-json-view';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ReportQueryForm from './component/ReportQueryForm';
import { splitType, includeTable } from './utils/report-type';

@Form.create()
@connect(({ report, loading }) => ({
  report,
  loading: loading.models.report,
}))
class ReportQuery extends React.Component {
  state = {
    queryDataLoading: false, // 查询数据加载状态
    queryError: false, // 查询报错
    errMsg: '',
    reportId: null,
    report: {},
    queryArgs: [],
    hasTable: false, // 是否有表格
    // graph: [], // 显示图形类型
    dataSource: [],
    columns: [],
    sql: null, // 运行时sql
    resultData: {},
  };

  componentDidMount() {
    const {
      match: { params },
      history,
    } = this.props;
    const { reportId } = params;
    this.setState(
      {
        reportId,
      },
      () => {
        this.loadReportInfoData();
      }
    );

    // 路由监听
    history.listen(route => {
      const { pathname } = route;
      const arr = pathname.trim().split('/');
      const tmpReportId = arr[3];
      if (reportId !== tmpReportId) {
        // 重新初始化state状态机
        this.setState(
          {
            reportId: tmpReportId,
            queryError: false,
            queryDataLoading: false,
            report: {},
            queryArgs: [],
            hasTable: false, // 是否有表格
            // graph: [], // 显示图形类型
            dataSource: [],
            columns: [],
            sql: null, // 运行时sql
          },
          () => {
            this.loadReportInfoData();
          }
        );
      }
    });
  }

  // 加载报表数据
  loadReportInfoData = () => {
    const { dispatch } = this.props;
    const { reportId } = this.state;
    dispatch({
      type: 'report/fetchDetail',
      payload: {
        reportId,
      },
      callback: data => {
        const { report, queryArgs } = data;
        const { type } = report; // 报表展示类型
        const graph = splitType(type);
        const hasTable = includeTable(graph);
        this.setState({
          queryArgs,
          report,
          // graph,
          hasTable,
        });
      },
    });
  };

  // 数据查询操作
  formQuery = fields => {
    const {
      report: { code },
    } = this.state;
    const { dispatch } = this.props;
    // 开启加载状态
    this.setState({
      queryDataLoading: true,
    });
    dispatch({
      type: 'report/queryData',
      payload: {
        reportCode: code,
        ...fields,
      },
      callback: (state, message, data) => {
        console.log(data);
        // 加载数据loading关闭
        this.setState({
          queryDataLoading: false,
        });

        if (state === 0 && data) {
          this.handlerData(data);
        } else {
          // 默认化状态
          this.setState({
            queryError: true,
            errMsg: message,
            dataSource: [],
            columns: [],
            sql: null,
            resultData: {},
          });
        }
      },
    });
  };

  // 处理查询数据
  handlerData = data => {
    const {
      columns,
      rows,
      extraInfo: { sql },
    } = data;
    const { hasTable } = this.state;
    this.setState({
      sql,
      resultData: data,
    });
    // 对表格数据进行处理
    if (hasTable) {
      const arr = [];
      if (columns) {
        columns.forEach(c => {
          arr.push({
            title: c.showName,
            dataIndex: c.name,
          });
        });
      }
      this.setState({
        queryError: false,
        dataSource: rows,
        columns: arr,
      });
    }
  };

  // 表单级联查询操作
  dependOnChange = params => {
    const { dispatch } = this.props;
    dispatch({
      type: 'report/queryLov',
      payload: {
        ...params,
      },
    });
  };

  // 获取表格行Key
  getRowKey = (record, index) => {
    return `${record[0]}_${index}`;
  };

  render() {
    const {
      queryArgs,
      report,
      hasTable,
      dataSource,
      columns,
      sql,
      queryDataLoading,
      loading,
      queryError,
      errMsg,
      resultData,
    } = this.state;
    const { name, comment, queryFieldLabelLen, queryFieldMediaLen } = report;
    const haveSql = sql && sql !== null && sql !== '';
    return (
      <Spin spinning={loading || queryDataLoading} delay={60} tip="数据查询中...">
        <PageHeaderWrapper title={name} content={comment}>
          <Card bordered={false}>
            <ReportQueryForm
              items={queryArgs}
              labelSpan={queryFieldLabelLen}
              mediaSpan={queryFieldMediaLen}
              dependOnChange={this.dependOnChange}
              onQueryClick={this.formQuery}
            />
          </Card>
          {haveSql && (
            <Card bordered={false} style={{ marginTop: '15px' }}>
              <Collapse accordion>
                <Collapse.Panel header="运行时SQL">
                  <p>{sql}</p>
                </Collapse.Panel>
              </Collapse>
            </Card>
          )}
          <Card bordered={false} style={{ marginTop: '15px' }}>
            {queryError && <Alert message="查询错误" showIcon type="error" description={errMsg} />}
            <Tabs defaultActiveKey="json1">
              <Tabs.TabPane key="json1" tab="JSON">
                {!queryError && <ReactJson src={resultData} />}
              </Tabs.TabPane>
              <Tabs.TabPane key="table" tab="表格">
                {!queryError && hasTable && (
                  <Table
                    size="small"
                    dataSource={dataSource}
                    rowKey={this.getRowKey}
                    columns={columns}
                  />
                )}
              </Tabs.TabPane>
            </Tabs>
          </Card>
        </PageHeaderWrapper>
      </Spin>
    );
  }
}

export default ReportQuery;
